<?php

namespace App\Library\Rms;

use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;

class RmsShopApi extends RmsBaseApi
{

    const SHOP_STATUS_ON   = 0; //正常
    const SHOP_STATUS_OFF  = 1; //闭店
    const SHOP_STATUS_WAIT = 2; //筹备中
    const SHOP_STATUS_TEXT = [
        self::SHOP_STATUS_ON   => '正常',
        self::SHOP_STATUS_OFF  => '闭店',
        self::SHOP_STATUS_WAIT => '筹备中',
    ];

    const SHOP_TYPE_LEAGUE  = 1; // 加盟
    const SHOP_TYPE_DIRECT  = 2; // 直营
    const SHOP_TYPE_MAPPING = [
        self::SHOP_TYPE_LEAGUE => '加盟店',
        self::SHOP_TYPE_DIRECT => '直营店',
    ];

    const SHOP_STATUS_NORMAL  = 0; // 正常
    const SHOP_STATUS_BAN     = 1; // 禁用
    const SHOP_STATUS_PREPARE = 2; // 筹备中

    const SOURCE_TYPE_WM_MT = 3; // 美团外卖
    const SOURCE_TYPE_WM_ELM = 4; // 饿了么外卖
    const SOURCE_TYPE_DP = 5; // 点评
    const SOURCE_TYPE_DY = 7; // 抖音


    // 角色的平台类型
    public const ROLE_WEB_TYPE      = 1; // 运营中心
    public const ROLE_POS_TYPE      = 2; // 收银机
    public const ROLE_BUSINESS_TYPE = 3; // 商家 APP

    const ROLE_TYPE_LIST = [
        self::ROLE_WEB_TYPE      => 'WEB',
        self::ROLE_POS_TYPE      => 'POS',
        self::ROLE_BUSINESS_TYPE => '商家'
    ];


    /**
     * 建店
     * @param string $shopName
     * @param string $shopMobile
     * @param string $contact
     * @param int $type
     * @return array
     * @throws GuzzleException
     */
    public function createShop(
        string $shopName,
        string $shopMobile,
        string $contact,
        int $shopCode,
        int $type = self::SHOP_TYPE_LEAGUE,
        int $status = self::SHOP_STATUS_PREPARE,
        int $adCityCode = 0,
        int $adRegionCode = 0,
        string $regionName = ''
    ) {
        $params = [
            'brandId'      => 1,
            'shopName'     => $shopName,
            'shopMobile'   => $shopMobile,
            'contact'      => $contact,
            'type'         => $type,
            'status'       => $status,
            'address'      => '',
            'shopCode'     => $shopCode,
            'adCityCode'   => $adCityCode,
            'adRegionCode' => $adRegionCode,
            'regionName'   => $regionName,
        ];

        return $this->rmsCurl->do('api/internal/shop/create', $params, 'POST');
    }

    /**
     * 检查开店用shopCode
     * @param int $shopCode
     * @return array
     * @throws GuzzleException
     */
    public function checkOpenShopCode(int $shopCode)
    {
        $params = [
            'shopCode' => $shopCode,
        ];

        return $this->rmsCurl->do('api/internal/shop/checkOpenShopCode', $params, 'GET');
    }

    /**
     * shopCode获取开店信息
     * @param int $shopCode
     * @return array
     * @throws GuzzleException
     */
    public function getShopByCode(int $shopCode)
    {
        $params = [
            'shopCode' => $shopCode,
            'brandId'  => 1,
        ];

        return $this->rmsCurl->do('api/internal/shop/getShopByCode', $params, 'GET');
    }

    /**
     * shopCodes批量获取开店信息
     * @param int $shopCode
     * @return array
     * @throws GuzzleException
     */
    public function getShopByCodes(array $shopCodes, array $fields = ['*'])
    {
        $params = [
            'shopCodes' => implode(',', $shopCodes),
            'brandId'   => 1,
            'fields'    => implode(',', $fields),
        ];

        return $this->rmsCurl->do('api/internal/shop/getShopByCodes', $params, 'GET');
    }

    /**
     * 获取省市区对应code
     * @param array $provinceCityArea
     * @return array
     * @throws GuzzleException
     */
    public function getAreaCodeByArea(array $provinceCityArea)
    {
        $params = [
            'area' => implode('-', $provinceCityArea),
        ];

        return $this->rmsCurl->do('api/internal/getAreaCodeByArea', $params, 'GET');
    }

    /**
     * 门店按照省的统计概览
     * @param array $provinceCodes
     * @param int $openStartTime
     * @param int $openEndTime
     * @return array
     * @throws GuzzleException
     */
    public function overviewByProvinceCodes(array $provinceCodes, int $openStartTime, int $openEndTime)
    {
        $params = [
            'provinceCodes' => $provinceCodes,
            'openStartTime' => $openStartTime,
            'openEndTime'   => $openEndTime,
        ];

        return $this->rmsCurl->do('api/internal/shop/overviewByProvinceCodes', $params, 'GET');
    }

    /**
     * 批量获取店铺信息by Ids
     * @param array $shopIds
     * @param array $fields
     * @return array
     * @throws GuzzleException
     */
    public function getShopByIds(array $shopIds, array $fields = [], bool $cached = false)
    {
        $params = [
            'shopIds' => implode(',', $shopIds),
            'fields'  => implode(',', $fields),
            'brandId' => 1,
        ];

        if ($cached) {
            $cacheKey = "getShopByIds:" . md5(json_encode($shopIds)) . ':' . md5(json_encode($fields));

            return Cache::remember($cacheKey, 300, function () use ($params) {
                return $this->rmsCurl->do('api/internal/shop/getShopInfos', $params, 'GET');
            });
        }

        return $this->rmsCurl->do('api/internal/shop/getShopInfos', $params, 'GET');
    }

    /**
     * 营业额
     * @param int $shopId
     * @param int $startTime
     * @param int $endTime
     * @return array
     * @throws GuzzleException
     */
    public function originalPrice(int $shopId, int $startTime, int $endTime)
    {
        $params = [
            'shopId'      => $shopId,
            'showStartAt' => $startTime,
            'showEndAt'   => $endTime,
        ];

        if (config('app.env') == 'pre') {
            $this->rmsCurl->setDomain('https://api.51kuafu.com/');
        }

        return $this->rmsCurl->do('api/internal/order/originalPrice', $params, 'GET');
    }

    /**
     * 获取N天营业数据
     * @param int $shopId
     * @param string $startDate
     * @param int $day
     * @return mixed
     */
    public function getBusinessData(int $shopId, string $startDate, int $day)
    {
        $params = [
            'shopId'    => $shopId,
            'startDate' => $startDate,
            'day'       => $day,
        ];

        return $this->rmsCurl->do('api/internal/shop/getStartBusinessData', $params, 'GET');
    }

    /**
     * 根据名称获取门店信息
     * @param string $name
     * @param array $fields
     * @return array
     * @throws GuzzleException
     */
    public function getShopByName(string $name, array $fields = ['*'])
    {
        $params = [
            'name'   => $name,
            'fields' => $fields,
        ];

        return $this->rmsCurl->do('api/internal/shop/getShopByName', $params, 'GET');
    }

    /**
     * 稽核门店范围筛选
     * @param string $provinceCode
     * @param string $cityCode
     * @param string $regionCode
     * @param int $status 详见self::SHOP_STATUS_
     * @param int $level 详见OpenShopSiteLocationModel::HOUSE_GRADE_SIFT_MAPPING
     * @param float $orderRatioStart 1=1%, 订货比start
     * @param float $orderRatioEnd
     * @param int $lastCruiseTime 最后巡店的时间戳
     * @param int $pageSize
     * @param int $pageNum
     * @return array
     * @throws GuzzleException
     */
    public function cruiseShopFilter(
        string $provinceCode,
        string $cityCode,
        string $regionCode,
        ?int $status,
        int $level,
        float $orderRatioStart,
        float $orderRatioEnd,
        int $lastCruiseTime,
        array $shopIds,
        int $pageSize = 20,
        int $pageNum = 1
    ) {
        $params = [
            'provinceCode'    => $provinceCode,
            'cityCode'        => $cityCode,
            'regionCode'      => $regionCode,
            'status'          => $status,
            'level'           => $level,
            'orderRatioStart' => $orderRatioStart,
            'orderRatioEnd'   => $orderRatioEnd,
            'lastCruiseTime'  => $lastCruiseTime,
            'shopIds'         => $shopIds,
            'pageSize'        => $pageSize,
            'pageNum'         => $pageNum,
        ];

        return $this->rmsCurl->do('api/internal/shop/cruiseShopFilter', $params, 'GET');
    }

    /**
     * 门店风云榜数据
     * @param array $shopIds
     * @param array $fields
     * @return array
     * @throws GuzzleException]
     */
    public function shopBusiness(array $shopIds, array $fields = ['*'])
    {
        $params = [
            'shopIds' => $shopIds,
            'fields'  => $fields,
        ];

        if (config('app.env') == 'pre') {
            $this->rmsCurl->setDomain('https://api.51kuafu.com/');
        }

        return $this->rmsCurl->do('api/internal/shop/shopBusiness', $params, 'GET');
    }

    /**
     * 门店列表
     * @param array $shopIds
     * @param array $fields
     * @return array
     * @throws GuzzleException]
     */
    public function getRmsShopListByParams(string $searchWhere, array $withFields = ['*'])
    {
        $params = [
            'searchWhere' => $searchWhere,
            'withFields'  => implode(',', $withFields),
        ];

        return $this->rmsCurl->do('api/internal/shop/getShopList', $params, 'GET');
    }

    /**
     * 根据门店ID获得门店员工
     * @param int $shopId
     * @param bool $filterWebUser
     * @param bool $cache
     * @param string $type
     * @return array
     * @throws GuzzleException
     */
    public function getShopStaffListByShopId(int $shopId, bool $filterWebUser = false, bool $cache = false, string $type = ''): array
    {
        // 仅测试环境允许不过滤员工
//        if ($filterWebUser == false && !isTest()) {
//            $filterWebUser = true;
//        }
        $cacheKey = 'rms:shop:staff:list:' . $shopId;

        if ($cache) {
            $cacheData = Cache::get($cacheKey);
            if ($cacheData !== null) {
                return $cacheData;
            }
        }

        $params = [
            'filterWebUser' => $filterWebUser,
            'shopId'        => $shopId,
            'type'          => $type,// 员工平台类型
        ];

        $res = $this->rmsCurl->do('api/internal/shop/getShopStaffListByShopId', $params, 'GET');

        if ($cache) {
            Cache::put($cacheKey, $res, getSwitchCacheTime(120));
        }

        return $res;
    }

    /**
     * 解绑功能开通
     * @param int $shopId
     * @param int $sourceType
     * @return array
     * @throws GuzzleException
     */
    public function unbindFunctionOpen(int $shopId, int $sourceType): array
    {
        $params = [
            'shopId'     => $shopId,
            'sourceType' => $sourceType,
        ];

        return $this->rmsCurl->do('api/internal/shop/unbindFunctionOpen', $params, 'POST');
    }

    /**
     * 解绑富友
     * @param int $shopId
     * @return array
     */
    public function unbindFy(int $shopId): array
    {
        $params = [
            'shopId' => $shopId
        ];

        return $this->rmsCurl->do('api/internal/pay/delFyConfig', $params, 'POST');
    }

    public function getUserinfoWithShopAuth(string $authorization, int $brandId, int $shopId)
    {
        $params= [];

        return $this->rmsCurl->setHeader(['authorization' => $authorization, 'brandId' => $brandId, 'shopId' => $shopId])
                             ->do("api/merchant/user/getUserinfoWithShopAuth", $params, "GET");
    }

    /**
     * 获得门店相对30天的营业数据
     * @param int $shopId
     * @return array
     */
    public function indexCharts(
        int $shopId,
        int $showTimeTab,
        int $showStartAt,
        int $showEndAt,
        int $compareTimeTab,
        int $compareStartAt,
        int $compareEndAt
    ): array
    {
        $params = [
            'shopId'         => $shopId,
            'showTimeTab'    => $showTimeTab,
            'showStartAt'    => $showStartAt,
            'showEndAt'      => $showEndAt,
            'compareTimeTab' => $compareTimeTab,
            'compareStartAt' => $compareStartAt,
            'compareEndAt'   => $compareEndAt,
            'statisticsType' => 2
        ];

        return $this->rmsCurl->setHeader(['shopId' => $shopId])->do('api/internal/order/indexCharts', $params, 'GET');
    }
}
